<template>
  <el-dialog :title="form.id ? '编辑' : '新增'" v-model="visible" :close-on-click-modal="false" draggable>
    <el-form ref="dataFormRef" :model="form" :rules="dataRules" formDialogRef label-width="90px" v-loading="loading">
      <el-row :gutter="24">
        <el-col :span="24" class="mb20">
          <el-form-item label="规则名称" label-width="150px" prop="ruleName">
            <el-input v-model="form.ruleName" placeholder="请输入规则名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12" class="mb20">
          <el-form-item label="打卡开始时间" label-width="150px" prop="checkStartTime">
            <el-time-picker arrow-control format="HH:mm:ss" value-format="HH:mm:ss" v-model="form.checkStartTime"
              placeholder="请选择打卡开始时间">
            </el-time-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="打卡结束时间" label-width="150px" prop="checkEndTime">
            <el-time-picker arrow-control format="HH:mm:ss" value-format="HH:mm:ss" v-model="form.checkEndTime"
              placeholder="请选择打卡结束时间">
            </el-time-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="打卡开始日期偏移" label-width="150px" prop="checkStartShifting">

            <el-select v-model="form.checkStartShifting" clearable placeholder="请选择打卡开始日期偏移">
              <el-option v-for="item in startShiftings" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>

          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="打卡结束日期偏移" label-width="150px" prop="checkEndShifting">
            <el-select v-model="form.checkEndShifting" clearable placeholder="请选择打卡结束日期偏移">
              <el-option v-for="item in startShiftings" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="最长迟到时限(分钟)" label-width="150px" prop="maxLateMinute">
            <el-input v-model="form.maxLateMinute" type="number" placeholder="请输入最长迟到时限" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="最长早退时限(分钟)" label-width="150px" prop="maxLeaveMinute">
            <el-input v-model="form.maxLeaveMinute" type="number" placeholder="请输入最长早退时限" />
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="上班开始时间" label-width="150px" prop="workStartTime">
            <el-time-picker arrow-control format="HH:mm:ss" value-format="HH:mm:ss" v-model="form.workStartTime"
              placeholder="请选择上班开始时间">
            </el-time-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="上班结束时间" label-width="150px" prop="workEndTime">
            <el-time-picker arrow-control format="HH:mm:ss" value-format="HH:mm:ss" v-model="form.workEndTime"
              placeholder="请选择上班结束时间">
            </el-time-picker>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="上班开始日期偏移" label-width="150px" prop="workStartShifting">
            <el-select v-model="form.workStartShifting" clearable placeholder="请选择上班开始日期偏移">
              <el-option v-for="item in startShiftings" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12" class="mb20">
          <el-form-item label="上班结束日期偏移" label-width="150px" prop="workEndShifting">
            <el-select v-model="form.workEndShifting" clearable placeholder="请选择上班开始日期偏移">
              <el-option v-for="item in startShiftings" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" class="mb20">
          <el-divider content-position="center">规则(子)信息</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddOrderItem">添加</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteOrderItem">删除</el-button>
            </el-col>
          </el-row>
          <el-table ref="OrderItem" :data="classesList" :row-class-name="rowOrderItemIndex" tooltip-effect="dark"
            style="width: 100%" @selection-change="handleOrderItemSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column label="工休开始时间">
              <template #default="scope">
                <el-time-picker arrow-control format="HH:mm:ss" value-format="HH:mm:ss"
                  v-model="scope.row.breakStartTime" placeholder="请选择工休开始时间"></el-time-picker>
              </template>
            </el-table-column>
            <el-table-column label="工休结束时间">
              <template #default="scope">
                <el-time-picker arrow-control format="HH:mm:ss" value-format="HH:mm:ss" v-model="scope.row.breakEndTime"
                  placeholder="请选择工休结束时间"></el-time-picker>
              </template>
            </el-table-column>
            <el-table-column label="工休开始日期偏移">
              <template #default="scope">
                <el-select v-model="scope.row.breakStartShifting" clearable placeholder="请选择工休开始日期偏移">
                  <el-option v-for="item in startShiftings" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="工休结束日期偏移">
              <template #default="scope">
                <el-select v-model="scope.row.breakEndShifting" clearable placeholder="请选择工休结束日期偏移">
                  <el-option v-for="item in startShiftings" :key="item.value" :label="item.label" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-col>

      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit" :disabled="loading">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="ClassesRulesDialog">
import { useDict } from '/@/hooks/dict';
import { useMessage } from "/@/hooks/message";
import { getObj, addObj, putObj } from '/@/api/personnel/classesRules'
import { rule } from '/@/utils/validate';
const emit = defineEmits(['refresh']);

// 定义变量内容
const dataFormRef = ref();
const visible = ref(false)
const loading = ref(false)
const checkedOrderItem = ref([]);
const classesList = ref([]);
/** (子)序号 */
const rowOrderItemIndex = ({ row, rowIndex }) => {
  row.index = rowIndex + 1
}
/** 单选框选中数据 */
const handleOrderItemSelectionChange = (selection: any) => {
  checkedOrderItem.value = selection
}
/** (子)添加按钮操作 */
const handleAddOrderItem = () => {
  let obj = {
    breakStartTime: '',
    breakEndTime: '',
    breakStartShifting: 0,
    breakEndShifting: 0
  }

  classesList.value.push(obj)
}
/** 预约(子)删除按钮操作 */
const handleDeleteOrderItem = () => {
  if (checkedOrderItem.value.length == 0) {
    // .alert('请先选择要删除(子)数据', '提示', {
    //   confirmButtonText: '确定'
    // })
  } else {
    checkedOrderItem.value.forEach((item: { index: any; }) => {
      for (let i = 0; i < classesList.value.length; i++) {
        if (classesList.value[i].index === item.index) {
          classesList.value.splice(i, 1)
          break
        }
      }
    })
    checkedOrderItem.value = []
  }
}
// 定义字典
const startShiftings = ref([{
  value: -1,
  label: "前一天"
}, {
  value: 0,
  label: "今天"
}, {
  value: 1,
  label: "后一天"
}]);
// 提交表单数据
const form = reactive({
  id: '',
  ruleName: '',
  checkStartTime: '',
  checkEndTime: '',
  checkStartShifting: '',
  checkEndShifting: '',
  maxLateMinute: '',
  maxLeaveMinute: '',
  workStartTime: '',
  workEndTime: '',
  workStartShifting: '',
  workEndShifting: '',
  workDuration: '',
  breaks: []
});

// 定义校验规则
const dataRules = ref({
})

// 打开弹窗
const openDialog = (id: string) => {
  visible.value = true
  classesList.value = []
  form.id = ''

  // 重置表单数据
  nextTick(() => {
    dataFormRef.value?.resetFields();
  });

  // 获取classesRules信息
  if (id) {
    form.id = id
    getclassesRulesData(id)
  }
};

// 提交
const onSubmit = async () => {
  // if (classesList.value.length == 0) {
  //   useMessage().error('请添加规则(子)信息');
  //   return
  // }
  form.breaks = classesList.value
  console.log('form', form);

  const valid = await dataFormRef.value.validate().catch(() => { });
  if (!valid) return false;

  try {
    loading.value = true;
    form.id ? await putObj(form) : await addObj(form);
    useMessage().success(form.id ? '修改成功' : '添加成功');
    visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};


// 初始化表单数据
const getclassesRulesData = (id: string) => {
  // 获取数据
  loading.value = true
  getObj(id).then((res: any) => {

    if (res.data.breaks != null) {
      classesList.value = res.data.breaks
    } else {
      classesList.value = []
    }
    Object.assign(form, res.data)
  }).finally(() => {
    loading.value = false
  })
};

// 暴露变量
defineExpose({
  openDialog
});
</script>